<!DOCTYPE html>
<html>
    <head>
        <title>Title</title>
        <meta charset="utf-8">
    </head>
    <body>
        <form action="/AjaxDemo/selectUserServlet" method="get">
            <h1>欢迎注册</h1>
            用户名：<input name="username" type="text" id="username">
            <span id="username_err" style="display:none;">用户名已被占用</span><br>
            密码：<input name="password" type="password"><br>
            <input value="注册" type="submit">
        </form>
        <script>
            //为用户名输入框绑定一个失去焦点onblur事件
            document.getElementById("username").onblur = function () {
                //1 用户名为用户输入的字符串
                var username = this.value;
                //2 创建核心对象
                var xhttp;
                if (window.XMLHttpRequest) {
                    xhttp = new XMLHttpRequest();
                } else {
                    // code for IE6, IE5
                    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }

                //3 建立连接
                xhttp.open("GET", "http://localhost:8080/AjaxDemo/selectUserServlet?username=" + username);
                //4 发送请求
                xhttp.send();
                //5 获取响应
                xhttp.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) {
                        // 通过 this.responseText 可以获取到服务端响应的数据
                        // alert(this.responseText);
                        // 判断用户名存在
                        if (this.responseText == "true") {
                            document.getElementById("username_err").style.display = 'none';
                        } else {
                            //若显示则将display属性值设为空字符串即可
                            document.getElementById("username_err").style.display = '';
                        }
                    }
                };
            }
        </script>
    </body>
</html>